import { Injectable } from '@angular/core';

import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import axios from 'axios';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RoutesRecognized, ResolveStart } from '@angular/router';
import { filter } from 'rxjs/operators';
declare var layui: any;
declare var layer: any;
declare var $: any;
declare var PDFObject: any;
import { UtilService } from '../services/util.service';
import { NzModalRef, NzFormatEmitEvent, NzModalService, NzMessageService } from 'ng-zorro-antd';
const httpOptions_www = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest' }) };
const httpOptions_form = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'X-Requested-With': 'XMLHttpRequest' }) };
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
const http_formData = { headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data', 'X-Requested-With': 'XMLHttpRequest' }) };
const httpText = { headers: new HttpHeaders({ 'Content-Type': 'text/html' }) };

@Injectable({
  providedIn: 'root'
})
export class PagesService {

  getUrl() {
    return "http://192.168.5.100:8080";
  }

  /**
   * 通用接口状态验证
   */
  codeValidation(data) {
    var flag = false;
    if (data.code == 100) {// 100失效
      // this.nzMessageService.info(data.message);
      this.loadClose();
      $('.layui-table-tips .layui-layer-content i.layui-icon-close').click();
      localStorage.setItem('loginMsg', data.message);
      this.router.navigate(['/auth/login']);
    } else {
      flag = true;
    }
    return flag;
  }

  /**
   * 获取添加接口返回生成的主键id
   */
  funPrimarykey(module, data) {
    if(module.utilService.isState[module.privIds] == 1){
      module['parmaryKeyData'] = data.object;
    }
  }

  /**
   * 匹配添加接口返回生成的主键id数据,操作为选中状态
   */
  matchingPrimarykey(module, res) {
    const data = res.data;
    if (module['parmaryKeyData']) {
      const obj = module['parmaryKeyData'];
      // console.log('parmaryKeyData',module['parmaryKeyData'],'data',res.data)
      data.forEach((item, index) => {
        let flag = true;
        for (let x in obj) {
          if (item[x] !== obj[x]) {
            flag = false;
            break;
          }
        }
        if (flag) {
          $(module['componentName'] + " div[lay-id='" + module['indexTableId'] + "'] .layui-table-box tbody tr[data-index='" + index + "']").addClass('layui-table-click').siblings().removeClass('layui-table-click');
          module['formInfo'](item);
        }
      });
    }
    delete module['parmaryKeyData'];
  }

  postPageText(pageUrl, postData) {
    return this.http.post(pageUrl, postData, httpText);
  }

  postPage(pageUrl, postData) {
    return this.http.post(pageUrl, postData, httpOptions);
  }
  postPage_form(pageUrl, postData) {
    return this.http.post(pageUrl, postData, httpOptions_form);
  }
  postPage_formData(pageUrl, postData) {
    return this.http.post(pageUrl, postData, http_formData);
  }
  getPage(url) {
    return this.http.get(url);
  }


  /**
   * 单据明细子表查询
   */
  infoSelect = '/erp/system/docdtl/docdtlview?1=1'


  /**
   * 单条单据明细录入
   */
  oneInfoAdd(json) {
    return this.http.post('/erp/system/docdtl/docdtlentering', json, httpOptions);
  }

  /**
   * 多行单据明细验证
   */
  moreInfoVis(json) {
    return this.http.post('/erp/system/docdtl/docdtlverify', json, httpOptions);
  }

  /**
   * 多行单据明细录入
   */
  moreInfoAdd(json) {
    return this.http.post('/erp/system/docdtl/docdtladd', json, httpOptions);
  }

  /**
   * 单据明细删除
   */
  infoDelete(json) {
    return this.http.post('/erp/system/docdtl/docdtldelete', json, httpOptions);
  }

  /**
   * 单据明细修改
   */
  infoUpdate(json) {
    return this.http.post('/erp/system/docdtl/docdtlupdate', json, httpOptions);
  }

  /**
   * 单据明细保存
   */
  infoSub(json) {
    return this.http.post('/erp/system/docdtl/docdtlsave', json, httpOptions);
  }

  /**
   * 单据明细取消
   */
  infoReset(json) {
    return this.http.post('/erp/system/docdtl/docdtlcancel', json, httpOptions);
  }

  /**
   * 单据明细汇总
   */
  infoSummary(json) {
    return this.http.post('/erp/system/docdtl/docdtlcollect', json, httpOptions);
  }

  /* 
  field1 = []             table表格1-主表列字段集合
  data1 = {}              table表格1-主表对象数据集合
  data1_dis = {}          table表格1-主表对象禁用集合
  data1_hid = {}          table表格1-主表对象显示集合
  data1_sel = []          table表格1-主表下拉框数据集合
  data1_selValue = {}     table表格1-主表下拉框默认赋值集合
  data1_att = []          table表格1-主表自定义属性数据集合
  data1_attsel = []       table表格1-主表自定义属性下拉框数据集合
  data1_attselValue = {}  table表格1-主表自定义属性下拉框默认赋值集合
  data1_fieldConfig = []  table表格1-动态列中“fieldConfigParameter”为“true”的数据集
  data1_parmKey = ''      table表格1-动态列类别标识
  notNullFields1=[]       table表格1-主表非空字段数据集
  addNotEditFields1=[]    table表格1-主表添加不可编辑字段
  updateNotEditFields1=[] table表格1-主表修改不可编辑字段

  submit1 = false         弹窗编辑--提交按钮禁用状态
  submit2 = false         弹窗编辑--提交按钮禁用状态
  edit_updata=true        主从编辑--修改按钮隐藏状态
  edit_sub=true           主从编辑--提交按钮隐藏状态
  isCourse_gn = true      表单“功能”按钮禁用状态
  functionName=null       “功能”名称
  functionData=[]         “功能”数据
  tbdata={}               主表table选中数据
  */
  /**
   * 模块数据初始化
   * @param module 操作模块
   * @param num 操作数据标识
   * @param parmKey 动态列类别标识
   */
  initData(module, num, parmKey) {
    for (let i = 1; i <= num; i++) {
      module['field' + i] = [];
      module['data' + i] = {};
      module['data' + i + '_dis'] = {};
      module['data' + i + '_hid'] = {};
      module['data' + i + '_sel'] = [];
      module['data' + i + '_selValue'] = {};
      module['data' + i + '_att'] = [];
      module['data' + i + '_attsel'] = [];
      module['data' + i + '_attselValue'] = {};
      module['data' + i + '_fieldConfig'] = [];
      module['data' + i + '_parmKey'] = parmKey[i - 1];
      module['notNullFields' + i] = [];
      module['addNotEditFields' + i] = [];
      module['updateNotEditFields' + i] = [];
    }
    module['submit1'] = false;
    module['submit2'] = false;
    module['edit_updata'] = true;
    module['edit_sub'] = true;
    module['isCourse_gn'] = true;
    module['functionName'] = null;
    module['functionData'] = [];
    module['tbdata'] = {};
  }

  /**
   * 新-通用动态列,只查询
   * @param module 操作模块
   * @param num 操作表格标识
   * @param funcName 刷新表格方法（动态列加载完成后，默认执行table()）
   * @param loadRule 动态列加载参数规则
   * @param checkbox 可选参数，传1为多选表格
   */
  dynamicFieldSelect(module, num, funcName, loadRule, checkbox?, funcName2?) {
    this.http.post('/erp/common/fields/getdynamiclistfieldsbymodule/general',
      { moduleCode: module['data' + num + '_parmKey'], loadRule: loadRule }, httpOptions).subscribe((data: any) => {
        if (this.codeValidation(data)) {
          if (data.code == 200) {
            const datas = data.object;
            if (checkbox == 1) {
              module['field' + num] = module.utilService.filed_list(datas, checkbox);
            } else {
              module['field' + num] = module.utilService.filed_list(datas);
            }
            for (let i = 0; i < datas.length; i++) {
              module['searchData'][datas[i]['fieldValue']] = '';
            }
            if (funcName) {
              module[funcName]();
            }
            if (funcName2) {
              module[funcName2]();
            }
          } else {
            layer.msg(data.message);
          }
        }
      });
  }

  /**
   * 新-通用动态列
   * @param module 操作模块
   * @param num 操作表格标识
   * @param funcName 刷新表格方法（动态列加载完成后，默认执行table()）
   * @param loadRule 动态列加载参数规则
   * @param filed_list 表格字段列表
   * @param filed_parm1 表格字段列表参数1
   * @param filed_parm2 表格字段列表参数2
   * @param filed_parm3 表格字段列表参数3
   */
  dynamicField(module, num, funcName, loadRule, filed_list, filed_parm1?, filed_parm2?, filed_parm3?) {
    this.http.post('/erp/common/fields/getdynamiclistfieldsbymodule/general',
      { moduleCode: module['data' + num + '_parmKey'], loadRule: loadRule }, httpOptions).subscribe((data: any) => {
        if (this.codeValidation(data)) {
          if (data.code == 200) {
            const datas = data.object;
            module['dynamic' + num] = datas;
            module['data' + num + '_fieldConfig'] = [];
            for (let i = 0; i < datas.length; i++) {
              if (datas[i]['fieldConfigParameter']) {
                module['data' + num + '_fieldConfig'].push(datas[i]);
              }
            }
            if (filed_parm3) {
              module['field' + num] = module.utilService[filed_list](datas, filed_parm1, filed_parm2, filed_parm3);
            } else if (filed_parm2) {
              module['field' + num] = module.utilService[filed_list](datas, filed_parm1, filed_parm2);
            } else if (filed_parm1) {
              module['field' + num] = module.utilService[filed_list](datas, filed_parm1);
            } else {
              module['field' + num] = module.utilService[filed_list](datas);
            }
            module['data' + num + '_selValue'] = this.utilService.selectDefaultValue(datas);
            if (module['fieldIndexParam'] && num === 1) {
              module['fieldIndexParam'] = this.fieldIndexParam(data.object);
            }
            if (!module['data' + num + '_hid']) {
              module['data' + num + '_hid'] = [];
            }
            module['sysPrintKey'] = '';
            for (let i = 0; i < datas.length; i++) {
              if (datas[i]['sysPrintKey'] === true) {
                module['sysPrintKey'] = datas[i]['fieldValue'];
              }
              module['data' + num][datas[i]['fieldValue']] = '';
              module['data' + num + '_dis'][datas[i]['fieldValue']] = true;
              module['data' + num + '_hid'][datas[i]['fieldValue']] = false;
            }
            if (num === 1) {
              this.urlTable(module);
            }
            if (funcName) {
              module[funcName]();
            }

          } else {
            layer.msg(data.message);
          }
        }
      });
  }


  /**
   * 新-通用动态列-单据明细
   */
  dynamicFieldDtl(moduleCode, loadRule, parameter) {
    return this.http.post('/erp/common/fields/getdynamiclistfieldsbymodule/docdtl',
      { moduleCode: moduleCode, loadRule: loadRule, parameter: parameter }, httpOptions);
  }


  /**
   * 新-通用动态列-聚合接口
   * @param module 操作模块
   * @param num 操作表格标识
   * @param flag 操作方式：0为修改，1为添加
   */
  dynamicFieldConfig(module, num, flag, fun?) {
    let parameter = { switchUnitId: module['switchUnitId'] === undefined ? '' : module['switchUnitId'].toString() };
    for (let i = 0; i < module['data' + num + '_fieldConfig'].length; i++) {
      var config = '';
      var para = module['data' + num][module['data' + num + '_fieldConfig'][i]['fieldValue']];
      if (para !== undefined && para !== null) {
        config = para.toString();
      }
      parameter[module['data' + num + '_fieldConfig'][i]['fieldValue']] = config;
    }
    return this.http.post('/erp/common/fields/getgeneralfieldconfig',
      { moduleCode: module['data' + num + '_parmKey'], parameter: parameter }, httpOptions).subscribe((data: any) => {
        if (this.codeValidation(data)) {
          if (data.code == 200) {
            if (module['attr_data' + num]) {
              module['attr_data' + num] = data.object;
            }
            module['notNullFields' + num] = data.object.notNullFields;
            module['addNotEditFields' + num] = data.object.addNotEditFields;
            module['updateNotEditFields' + num] = data.object.updateNotEditFields;
            this.notNullEdit(module, num, flag);
          } else {
            layer.msg(data.message);
          }
        }
      });
  }


  /**
     * 新-通用动态列-聚合接口(商品品种明细聚合接口传值)
     * @param module 操作模块
     * @param num 操作表格标识
     * @param flag 操作方式：0为修改，1为添加
     */
  dynamicFieldConfig2(module, num, flag, fun?) {
    let parameter = { switchUnitId: module['switchUnitId'] === undefined ? '' : module['switchUnitId'] };
    for (let i = 0; i < module['data' + num + '_fieldConfig'].length; i++) {
      parameter[module['data' + num + '_fieldConfig'][i]['fieldValue']] = module['data' + num][module['data' + num + '_fieldConfig'][i]['fieldValue']];
    }
    return this.http.post('/erp/common/fields/getgeneralfieldconfig',
      { moduleCode: module['data' + num + '_parmKey'], parameter: parameter }, httpOptions).subscribe((data: any) => {
        if (this.codeValidation(data)) {
          if (data.code == 200) {
            for (let i of module['attr_data' + num]) {
              for (let ii of data.object.notNullFields) {
                if (i.fieldValue == ii.tableFlie) {
                  if (i.hideField == true) {
                    const index = data.object.notNullFields.findIndex(text => text.tableFlie === i.fieldValue)
                    data.object.notNullFields.splice(index, 1);
                  }
                }
              }
            }
            module['notNullFields' + num] = data.object.notNullFields;
            module['addNotEditFields' + num] = data.object.addNotEditFields;
            module['updateNotEditFields' + num] = data.object.updateNotEditFields;
            this.notNullEdit(module, num, flag);
          } else {
            layer.msg(data.message);
          }
        }
      });
  }


  /**
  * 设置编辑时不可编辑应用
  * @param module 操作模块
  * @param num 操作表格标识
  * @param flag 操作方式：0为修改，1为添加
  */
  notNullEdit(module, num, flag) {
    this.notNullFields(module, num);
    this.notEditFields(module, num, flag);
  }

  /**
   * 设置字段颜色初始化
   * @param module 操作模块
   * @param num 操作表格标识
   */
  fieldColor(module, num) {
    for (let i in module['data' + num]) {
      $(' .' + i + ' p span').css('color', this.utilService.fieldTrueColor);
    }
  }

  /**
   * 设置编辑时必填字段标红
   * @param module 操作模块
   * @param num 操作表格标识
   */
  notNullFields(module, num) {
    setTimeout(() => {
      this.fieldColor(module, num);
      for (let i = 0; i < module['notNullFields' + num].length; i++) {
        if (module.utilService.isState[module.privIds] === -1) {
          $('nz-modal .' + module['notNullFields' + num][i].tableFlie + ' p span').css('color', this.utilService.fieldFalseColor);
        } else {
          $(module['componentName'] + ' .' + module['notNullFields' + num][i].tableFlie + ' p span').css('color', this.utilService.fieldFalseColor);
          $('nz-modal .' + module['notNullFields' + num][i].tableFlie + ' p span').css('color', this.utilService.fieldFalseColor);
        }
      }
      if (module['data' + num + '_att']) {
        module['data' + num + '_att'].forEach((item, index) => {
          if (item.valReqd) {
            if (module.utilService.isState[module.privIds] === -1) {
              $('nz-modal .' + item.propId + " span:first-child").css("color", this.utilService.fieldFalseColor);
            } else {
              $(module['componentName'] + ' .' + item.propId + " span:first-child").css("color", this.utilService.fieldFalseColor);
              $('nz-modal .' + item.propId + " span:first-child").css("color", this.utilService.fieldFalseColor);
            }
          }
        });
      }
    }, this.utilService.setTime1);
  }

  /**
  * 设置操作时不可编辑字段
  * @param module 操作模块
  * @param num 操作表格标识
  * @param flag 操作方式：0为修改，1为添加
  */
  notEditFields(module, num, flag) {
    for (let i in module['data' + num + '_dis']) {
      module['data' + num + '_dis'][i] = false;
    }
    if (flag === 0) {
      for (let i = 0; i < module['updateNotEditFields' + num].length; i++) {
        module['data' + num + '_dis'][module['updateNotEditFields' + num][i].tableFlie] = true;
      }
    } else if (flag === 1) {
      for (let i = 0; i < module['addNotEditFields' + num].length; i++) {
        module['data' + num + '_dis'][module['addNotEditFields' + num][i].tableFlie] = true;
      }
    }
  }

  /**
   * 自定义属性字段查询
   * @param module 操作模块
   * @param num 操作表格标识
   * @param type 操作模块标识
   */
  attField(module, num, type) {
    this.http.post('/erp/attrDef/attrAndName', Object.assign({}, { modularType: type }, module['data' + num]), httpOptions).subscribe((data: any) => {
      if (this.codeValidation(data)) {
        if (data.code == 200) {
          module['data' + num + '_att'] = data.object;
          module['data' + num + '_att'].forEach((item, index) => {
            module['data' + num + '_att'][index][item.propId] = false;
          });
          /**
           * 添加状态默认赋第一个下拉值
           */
          if (module['data' + num + '_att'] && module.utilService.isState[module.privIds] === 1) {
            var att = module['data' + num + '_att'];
            for (let i = 0; i < att.length; i++) {
              if (att[i]['propType'] === 'PULLDOWN' && att[i]['referValue'] !== null) {
                if (att[i]['referValue'].length > 0) {
                  att[i]['defaultValue'] = att[i]['referValue'][0]['tableFlie'];
                  att[i]['defaultValueCp'] = att[i]['referValue'][0]['fileName'];
                }
              }
            }
          }

        }
      }
    });
  }


  /**
   * 判断是否可以修改删除：
   * @param module 操作模块
   * @param url 接口地址
   * isEdit = { update: 1, delete: 1 };
   * "update": 1 时主表可修改、子表可增加修改删除
   * "delete": 1 时主表可删除
   */
  isUpdateOrDelete(module, url) {
    return this.http.post(url, module['data1']).subscribe((data: any) => {
      if (this.codeValidation(data)) {
        if (data.code == 200) {
          module['isEdit'] = data.object;
        }
      }
    });
  }


  /**
   * 模块提交时必填字段验证
   * @param module 操作模块
   * @param num 操作表格标识
   */
  notNullSubmit(module, num) {
    let flag = true;
    if (module['data' + num + '_att']) {
      var att = module['data' + num + '_att'];
      for (let i = 0; i < att.length; i++) {
        if (att[i]['propType'] === 'DECIMAL' && att[i]['defaultValue']) {
          if (att[i].dataDec != null) {
            if (att[i].dataDec == 0) {
              if (att[i]['defaultValue'].toString().indexOf('.') != -1) {
                layer.msg(att[i]['propName'] + '小数位数不正确！');
                flag = false;
                break;
              }
            } else {
              const decimal = this.utilService.onDecimal(Number(att[i].dataDec));
              if (!decimal.test(att[i]['defaultValue'])) {
                layer.msg(att[i]['propName'] + '小数位数不正确！');
                flag = false;
                break;
              }
            }
          }

        }
        if (att[i]['valReqd'] && !att[i]['defaultValue']) {
          layer.msg(att[i]['propName'] + '不能为空！');
          flag = false;
          break;
        }
      }
    }
    if (flag) {
      for (let i = 0; i < module['notNullFields' + num].length; i++) {
        if (!this.utilService.patrn.test(module['data' + num][module['notNullFields' + num][i].tableFlie]) ||
          module['data' + num][module['notNullFields' + num][i].tableFlie] === null) {
          layer.msg(module['notNullFields' + num][i].fileName + '不能为空！');
          flag = false;
          break;
        }
      }
    }
    return flag;
  }

  /**
   * 验证主表表单状态是否走聚合接口
   * @param module 操作模块
   */
  stateFlag(module) {
    return Boolean(module.utilService.isState[module.privIds] === 0 || module.utilService.isState[module.privIds] === 1);
  }

  /**
   * 验证从表是否加载
   * @param module 操作模块
   */
  viceFlag(module) {
    return Boolean(JSON.stringify(module.tbdata) !== '{}');
  }

  /**
   * 单模块主表单据打印方法
   * @param module 操作模块
   */
  printBut(module) {
    module['printList'] = [];
    const privList = JSON.parse(localStorage.getItem('privList'));
    for (let i = 0; i < privList.length; i++) {
      if (privList[i]['privId'] === module['privIds'] && privList[i]['printId'] !== null && privList[i]['printType'] !== null) {
        this.http.post('/erp/print/tempOption', { printId: privList[i]['printId'], printType: privList[i]['printType'] }, httpOptions)
          .subscribe((data: any) => {
            module['printList'] = data.object.tempName;
          });
        break;
      }
    }
  }

  /**
   * 单模块主表单据打印执行
   * @param module 操作模块
   */
  printSub(module, e) {
    const privList = JSON.parse(localStorage.getItem('privList'));
    for (let i = 0; i < privList.length; i++) {
      if (privList[i]['privId'] === module['privIds'] && privList[i]['printId'] !== null && privList[i]['printType'] !== null) {
        const data = {
          tempName: e, printId: privList[i]['printId'], printType: privList[i]['printType'],
          data: module['tbdata'][module['sysPrintKey']], switchUnitId: module['switchUnitId']
        }
        this.pdfFile('/erp/print/print', data, 'printId', '.pdf');
      }
    }
  }


  /**
   * 通用post提交操作方法（增、删、改）
   * @param module 操作模块
   * @param url  接口地址
   * @param json 接口参数
   * @param msg message提示弹窗方式：
   * 0为接口返回立即执行，1为接口返回非200执行，2为接口返回200执行，其它不提示
   * @param but 按钮隐藏或禁用名称：
   * ‘submit1’为主表弹窗提交按钮禁用，‘submit2’为子表弹窗提交按钮禁用，‘edit_sub’为主从表确定按钮隐藏，其它不操作
   * @param way 参数赋值方式：
   * ''空为不赋值，字符串为取接口返回值（aaa=data.object）
   * 1为集合赋值方式module['data' + num][i]=pdata[i]==null?"":pdata[i] ，2位集合赋值方式module['data' + num][pdata[i]["name"]]=pdata[i]["value"]==null?"":pdata[i]["value"]
   * @param func1 接口返回200后执行方法1
   * @param func2 接口返回200后执行方法2
   * @param func3 接口返回200后执行方法3
   * @param func4 接口返回200后执行方法4
   */
  postSubmit(module, url, json, msg, but, way, func1?, func2?, func3?, func4?) {
    this.http.post(url, json, httpOptions).subscribe((data: any) => {
    });
  }

  /**
   * select下拉数据接口
   * @param module 操作模块
   * @param url 接口地址
   * @param json 接口参数
   * @param num 表单赋值数量
   */
  selectList(module, url, json, num) {
    this.http.post(url, json).subscribe((data: any) => {
      if (this.codeValidation(data)) {
        if (data.code == 200) {
          for (let p in data.object) {
            for (let i = 1; i <= num; i++) {
              module['data' + i + '_sel'][p] = data.object[p];
            }
          }
        }
      }
    });
  }

  /**
   * select动态列模式下拉取默认值（添加操作）
   * @param module 操作模块
   * @param num 被操作表单标识
   */
  selectIsValue(module, num) {
    for (let i in module['data' + num + '_sel']) {
      if (module['data' + num + '_sel'][i].length > 0) {
        module['data' + num][i] = this.utilService.selectEditValue(i, module['data' + num + '_selValue'][i], module['data' + num + '_sel'][i]);
        module['data' + num][i + 'Cp'] = this.utilService.selectEditName(i, module['data' + num + '_selValue'][i], module['data' + num + '_sel'][i]);
      }
    }
    for (let i=0;i<module['dynamic' + num].length;i++) {
      if (module['dynamic' + num][i]['viewFieldType']==='input') {
        module['data' + num][module['dynamic' + num][i]['fieldValue']] = module['dynamic' + num][i]['defaultValue'];
      }
    }
  }

  /**
  * select动态列模式下拉取默认值（自定义下拉模式）
  * @param module 操作模块
  * @param num 被操作表单标识
  */
  selectIsValue2(module, num, name, value) {
    module['data' + num][name] = this.utilService.selectEditValue(name, module['data' + num + '_selValue'][name], module['data' + num + '_sel'][name], value);
    module['data' + num][name + 'Cp'] = this.utilService.selectEditName(name, module['data' + num + '_selValue'][name], module['data' + num + '_sel'][name], value);

  }

  /**
   * 功能下拉数据接口
   * @param module 操作模块
   * @param url 接口地址
   * @param json 接口参数
   * @param num 多个功能下拉传值数量,不传默认为1
   */
  functionList(module, url, json, num?) {
    this.http.post(url, json).subscribe((data: any) => {
      if (this.codeValidation(data)) {
        if (data.code == 200) {
          if (data.object != null) {
            if (num) {
              module['functionData' + num] = data.object;
            } else {
              module['functionData'] = data.object;
            }
          }
        }
      }
    });
  }

  /**
   * 功能数据执行接口
   * @param module 操作模块
   * @param url 接口地址
   * @param json 接口参数
   * @param num 多个功能下拉传值数量,不传默认为1
   */
  functionSub(module, url, json, num?) {
    this.http.post(url.operationUrl, json).subscribe((data: any) => {
      if (this.codeValidation(data)) {
        layer.msg(data.message)
        if (num) {
          module['functionName' + num] = null;
        } else {
          module['functionName'] = null;
        }
        if (data.code == 200) {
          module.table();
        }
      }
    });
  }

  /**
   * 文件下载（单文件）
   * @param url 接口地址
   * @param json 访问参数
   * @param name 文件名称
   * @param type 文件类型
   */
  downloadFile(url, json, name, type) {
    axios({
      method: 'post',
      url: url,
      data: json,
      responseType: 'arraybuffer',
    })
      .then(res => {
        // 假设 data 是返回来的二进制数据
        const datas = res.data
        const url = window.URL.createObjectURL(new Blob([datas], {}));
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url;
        link.setAttribute('download', json[name] + type);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
  }

  /**
   * 文件下载（多文件）
   * @param url 接口地址
   * @param json 访问参数
   * @param name 文件名称
   * @param type 文件类型
   */
  pdfFile(url, json, name, type) {
    this.postPage(url, json).subscribe((data: any) => {
      if (this.codeValidation(data)) {
        if (data.code == 200) {
          const datas = data.object
          if (datas.action === 1) {//批量预览打印
            for (var i = 0; i < datas['fileList'].length; i++) {
              this['url' + i] = window.URL.createObjectURL(new Blob([this.urlBase64ToUint8Array(datas['fileList'][i]['file'])], { type: "application/pdf" }));
              this['link' + i] = document.createElement('a')
              this['link' + i].style.display = 'none'
              this['link' + i].href = this['url' + i];
              this['link' + i].setAttribute('target', '_blank');
              this['link' + i].click();
            }
          } else {//批量直接打印

          }

        } else {
          layer.msg(data.message);
        }
      }
    });

    /* axios({
      method: 'post',
      url: url,
      data: json,
      responseType: 'arraybuffer',
    }).then(res => {
      console.log(res.data, 'res.data')
      // 假设 data 是返回来的二进制数据
       const datas = res.data
       const url = window.URL.createObjectURL(new Blob([datas], { type: "application/pdf" }));
       const link = document.createElement('a')
       link.style.display = 'none'
       link.href = url;
       // link.setAttribute('download', json[name] + '.pdf');
       link.setAttribute('title', json[name]);
       link.setAttribute('name', json[name]);
       link.setAttribute('target', '_blank');
       document.body.appendChild(link);
       link.click();
       // new PDFObject({ url: "/assets/js/pdfobject.pdf" }).embed();
       document.body.removeChild(link);
    }) */

  }

  string2buffer(str) {
    // 首先将字符串转为16进制
    let val = ""
    for (let i = 0; i < str.length; i++) {
      if (val === '') {
        val = str.charCodeAt(i).toString(16)
      } else {
        val += ',' + str.charCodeAt(i).toString(16)
      }
    }
    // 将16进制转化为ArrayBuffer
    return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16)
    })).buffer
  }


  //ArrayBuffer转字符串
  ab2str(u, f) {
    var b = new Blob([u]);
    var r = new FileReader();
    r.readAsText(b, 'utf-8');
    r.onload = function () { if (f) f.call(null, r.result) }
  }
  //字符串转字符串ArrayBuffer
  str2ab(s, f) {
    var b = new Blob([s], { type: 'text/plain' });
    var r = new FileReader();
    r.readAsArrayBuffer(b);
    r.onload = function () { if (f) f.call(null, r.result) }
  }

  urlBase64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
      .replace(/\-/g, '+')
      .replace(/_/g, '/');

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  }

  /**
   * 文件提交（单文件）
   * @param module 操作模块
   * @param num 操作表格标识
   * @param url 接口地址
   * @param fileName 上传文件字段名称
   * @param but 操作按钮（取消禁用）
   * @param fun1 接口执行正常后执行方法
   * @param fun2 接口执行正常后执行方法
   * @param fun3 接口执行正常后执行方法
   */
  uploadFileSub(module, num, url, fileName, but, fun1?, fun2?, fun3?) {
    if (!module['data' + num][fileName]) {
      delete module['data' + num][fileName];
    }
    var formData = new FormData();
    for (var x in module['data' + num]) {
      if (x === 'file') {
        formData.append(x, module['data' + num][x]);
      } else {
        formData.append(x, encodeURIComponent(module['data' + num][x]));
      }
    }
    $.ajax({
      type: 'post',
      url: url,
      data: formData,
      contentType: false,
      processData: false,
      success: (data: any) => {
        layer.msg(data.message);
        module[but] = false;
        if (data.code == 200) {
          if (fun1) {
            module[fun1]();
          }
          if (fun2) {
            module[fun2]();
          }
          if (fun3) {
            module[fun3]();
          }
        }
      }
    });
  }

  /**
   * 文件提交（多文件）
   * @param module 操作模块
   * @param url 接口地址
   * @param state 操作状态，0为修改,1为添加
   * @param subList 接口数据集合
   * @param fileName 上传文件字段名称
   * @param but 操作按钮（取消禁用）
   * @param fun1 接口执行正常后执行方法
   * @param fun2 接口执行正常后执行方法
   * @param fun3 接口执行正常后执行方法
   */
  uploadFileSubMore(module, url, state, subList, fileName, but, fun1?, fun2?, fun3?) {
    var indexList = subList['index'];
    var infoList = subList['info'];
    var formData = new FormData();
    for (var x in indexList) {
      formData.append(x, indexList[x]);
    }
    var flag = true;
    for (var i = 0; i < infoList.length; i++) {
      if (!infoList[i][fileName] && state === 1) {
        flag = false;
        layer.msg('未正确上传文件！');
        module[but] = false;
        break;
      } else if (!infoList[i][fileName]) {
        delete infoList[i][fileName];
      }
      for (var x in infoList[i]) {
        if (x === 'file') {
          formData.append('list[' + i + '].' + x, infoList[i][x]);
        } else {
          formData.append('list[' + i + '].' + x, encodeURIComponent(infoList[i][x]));
        }
      }
    }

    if (flag) {
      $.ajax({
        type: 'post',
        url: url,
        data: formData,
        contentType: false,
        processData: false,
        success: (data: any) => {
          layer.msg(data.message);
          module[but] = false;
          if (data.code == 200) {
            if (fun1) {
              module[fun1]();
            }
            if (fun2) {
              module[fun2]();
            }
            if (fun3) {
              module[fun3]();
            }
          }
        }
      });
    }

  }

  /**
   * 地区控件初始化
   * @param module 操作模块
   * @param num 被操作表单标识
   * @param flag 操作方式：0为修改，1为添加
   * @param provinceName 省名称（默认可不传）
   * @param cityName 市名称（默认可不传）
   * @param districtName 县名称（默认可不传）
   * @param addressName 地址名称（默认可不传）
   */
  cityInit(module, num, flag, provinceName?, cityName?, districtName?, addressName?) {
    let province = provinceName === undefined ? 'province' : provinceName;
    let city = cityName === undefined ? 'city' : cityName;
    let district = districtName === undefined ? 'district' : districtName;
    let address = addressName === undefined ? 'address' : addressName;
    setTimeout(() => {
      layui.use([ 'form'], (obj) => {
        var form = layui.form 
        $(module['componentName'] + ' #start').xcity();
        /**
         * 监听区县元素变化
         */
        $('select[lay-filter=area]').bind('DOMNodeInserted', (e) => {
          module['data' + num][province] = $('select[lay-filter=province] option:selected').text();
          module['data' + num][city] = $('select[lay-filter=city] option:selected').text();
          module['data' + num][district] = $('select[lay-filter=area] option:selected').text();
          module['data' + num][address] = module['data' + num][province] + module['data' + num][city] + module['data' + num][district];
        });
        /**
         * 插件中区县选择数据后相应字段赋值
         */
        form.on('select(area)', (data) => {
          module['data' + num][province] = $(data.elem).parents('.x-city').find('select[lay-filter=province]').val();
          module['data' + num][city] = $(data.elem).parents('.x-city').find('select[lay-filter=city]').val();
          module['data' + num][district] = data.value;
          module['data' + num][address] = module['data' + num][province] + module['data' + num][city] + module['data' + num][district];
        });

        $(module['componentName'] + ' #start').xcity(module['data' + num][province],
          module['data' + num][city], module['data' + num][district]);
        if (module.utilService.isState[module.privIds] != -1) {
          this.dynamicFieldConfig(module, num, flag);
        } else {
          this.cityDisabled(module);
        }
      });
    }, this.utilService.setTime1);
  }

  /**
   * 地区联动控件取消禁用
   * @param module 操作模块
   * @param provinceName 省名称（默认可不传）
   * @param cityName 市名称（默认可不传）
   * @param districtName 县名称（默认可不传）
   */
  cityNotDisabled(module, provinceName?, cityName?, districtName?) {
    let province = provinceName === undefined ? 'province' : provinceName;
    let city = cityName === undefined ? 'city' : cityName;
    let district = districtName === undefined ? 'district' : districtName;
    layui.use([ 'form'], (obj) => {
      var form = layui.form 
      $(module['componentName'] + ' #start .' + province + ' select').removeAttr('disabled');
      $(module['componentName'] + ' #start .' + city + ' select').removeAttr('disabled');
      $(module['componentName'] + ' #start .' + district + ' select').removeAttr('disabled');
      form.render('select');
    });
  }

  /**
   * 地区联动控件禁用
   * @param module 操作模块
    * @param provinceName 省名称（默认可不传）
   * @param cityName 市名称（默认可不传）
   * @param districtName 县名称（默认可不传）
   */
  cityDisabled(module, provinceName?, cityName?, districtName?) {
    let province = provinceName === undefined ? 'province' : provinceName;
    let city = cityName === undefined ? 'city' : cityName;
    let district = districtName === undefined ? 'district' : districtName;
    layui.use([ 'form'], (obj) => {
      var form = layui.form 
      $(module['componentName'] + ' #start .' + province + ' select').attr('disabled', 'disabled');
      $(module['componentName'] + ' #start .' + city + ' select').attr('disabled', 'disabled');
      $(module['componentName'] + ' #start .' + district + ' select').attr('disabled', 'disabled');
      form.render('select');
    });
  }

  /**
   * 是否显示单据明细
   * @param module 操作模块
   * @param componentName 模块标识名称
   * @param vicel_tableId 明细表格id
   */
  isDetail(module, componentName, vicel_tableId) {
    if (!module['isDetail']) {
      $(componentName + ' div[lay-id=' + vicel_tableId + ']').css('display', 'none');
    } else {
      $(componentName + ' div[lay-id=' + vicel_tableId + ']').css('display', 'block');
    }
  }


  /**
   * 商品弹窗动态列传参字段集合（明细操作传参使用）
   * @param fieldFull 主表动态列字段集合
   */
  fieldProdParam(fieldFull) {
    var filedlist = []
    if (fieldFull.length > 0) {
      for (var i = 0; i < fieldFull.length; i++) {
        if (fieldFull[i]['checked']) {
          filedlist.push({ field: fieldFull[i]["fieldValue"] })
        }
      }
    }
    return filedlist;
  }

  /**
   * 主表动态列主键传参字段集合（明细操作传参使用）
   * @param fieldFull 主表动态列字段集合
   */
  fieldIndexParam(fieldFull) {
    var filedlist = []
    if (fieldFull.length > 0) {
      for (var i = 0; i < fieldFull.length; i++) {
        if (fieldFull[i]['primaryKey']) {
          filedlist.push({ field: fieldFull[i]["fieldValue"] })
        }
      }
    }
    return filedlist;
  }

  /**
   * get请求url增加主表对应字段（单据明细使用）
   * docType  单据类型
   * fieldParam  自定义添加字段集合
   * data1  原主表数据集合
   */
  getEdidField(docType, url, fieldParam, data1) {
    url = url + '&docType=' + docType
    for (var i = 0; i < fieldParam.length; i++) {
      for (let o in data1) {
        if (fieldParam[i]['field'] === o) {
          url = url + '&' + fieldParam[i]['field'] + '=' + data1[o]
        }
      }
    }
    return url
  }

  /**
   * post请求json传参对象增加主表对应字段（单据明细使用）
   * docType  单据类型
   * data 新json对象集合
   * fieldParam  单据明细传参对象对应主表基准字段
   * data1  原主表数据对象集合
   */
  postEdidField(docType, data, fieldParam, data1) {
    data['docType'] = docType
    for (var i = 0; i < fieldParam.length; i++) {
      for (let o in data1) {
        if (fieldParam[i]['field'] === o) {
          data[fieldParam[i]['field']] = data1[o]
        }
      }
    }
    return data;
  }

  /**
   * post请求json动态列传参对象增加主表对应字段（单据明细使用）--old
   * http://erp.boyu.site:4999/web/#/5?page_id=2220
   * docType  单据类型
   * data 新json对象集合
   * fieldParam  单据明细传参对象对应主表基准字段
   * data1  原主表数据对象集合
   */
  postDtlVOField(docType, data, fieldParam, data1) {
    data['parameter'] = {}
    data['parameter']['docType'] = docType
    for (var i = 0; i < fieldParam.length; i++) {
      for (let o in data1) {
        if (fieldParam[i]['field'] === o) {
          data['parameter'][fieldParam[i]['field']] = data1[o]
        }
      }
    }
    return data;
  }

  /**
   * post请求json动态列传参对象增加主表对应字段（单据明细使用）--new
   * http://erp.boyu.site:4999/web/#/5?page_id=2485
   * docType  单据类型
   * data 新json对象集合
   * fieldParam  单据明细传参对象对应主表基准字段
   * data1  原主表数据对象集合
   */
  newDtlVOField(docType, data, fieldParam, data1) {
    data['parameter'] = {}
    data['parameter']['docType'] = docType
    for (var i = 0; i < fieldParam.length; i++) {
      for (let o in data1) {
        if (fieldParam[i]['field'] === o) {
          data['parameter'][fieldParam[i]['field']] = data1[o]
        }
      }
    }
    return data;
  }

  /**
   * post请求json传参带商品明细数组处理（单据明细使用）
   * docType  单据类型
   * data 新json对象数组集合
   * fieldParam  单据明细传参对象对应主表基准字段
   * fieldParam2  单据明细商品数组对应明细基准字段
   * data1  原主表数据对象集合
   * data2  现明细表数据数组集合
   * 1、商品明细按明细基准字段处理,保留所需字段
   * 2、添加主表对象基准数据
   * 3、主表对象基准数据+更新后商品明细，返回最终传参
   */
  postEdidFields(docType, data, fieldParam, fieldParam2, data1, data2) {
    let fields = []
    for (var i = 0; i < data2.length; i++) {
      let field = {}
      for (var p = 0; p < fieldParam2.length; p++) {
        for (let o in data2[i]) {
          if (fieldParam2[p]['field'] === o) {
            field[o] = data2[i][o]
          }
        }
      }
      fields.push(field)
    }
    let subJson = this.postEdidField(docType, data, fieldParam, data1);
    subJson['docDtlModels'] = fields
    subJson['docType'] = docType
    return subJson;
  }

  /**
   * post请求json传参带商品明细对象处理（双击修改）
   * docType  单据类型
   * data 新json对象数组集合
   * fieldParam  单据明细传参对象对应主表基准字段
   * fieldParam2  单据明细商品数组对应明细基准字段
   * data1  原主表数据对象集合
   * data2  现明细表数据对象
   * editFieldName 被修改字段名
   * editFieldValue 被修改字段值
   * 1、根据主键id基准字段“值” 匹配 明细基准字段“键”，取明细基准字段“值”，匹配数据对象的“键”，取匹配数据对象的“值”赋值给主键id基准字段
   * 2、被修改字段名，匹配 明细基准字段“值”，取明细基准字段“键”，被修改字段值赋值给取明细基准字段“键”
   * 3、更新商品明细传参数据格式
   * 4、添加主表对象基准数据
   * 5、主表对象基准数据+更新后商品明细，返回最终传参
   */
  postdbEdidField(docType, data, fieldParam, fieldParam2, data1, data2, editFieldName, editFieldValue) {
    let fields = []
    for (var i = 0; i < data2.length; i++) {
      let field = {}
      for (var p = 0; p < fieldParam2.length; p++) {
        for (let o in data2[i]) {
          if (fieldParam2[p]['field'] === o) {
            field[o] = data2[i][o]
            field[editFieldName] = editFieldValue
          }
        }
      }
      fields.push(field)
    }
    let subJson = this.postEdidField(docType, data, fieldParam, data1);
    subJson['docDtlModels'] = fields
    subJson['docType'] = docType
    return subJson;
  }

  /**
   * 组织通用弹窗验证
   * @param switchUnitId   操作组织id
   * @param unitNum   验证数据
   * @param unitType  数据类型（采购、销售、库存、零售......）
   * @param url       可选参数（不传为默认使用采购模块url验证接口，否则使用第4参数传递url）
   */
  getUnitOption(switchUnitId, unitNum, unitType, url?) {//---鼠标事件，输入编号查询组织信息,第4参数不传为默认使用采购模块验证接口，否则使用第4参数接口
    var urls
    if (!this.utilService.patrn.test(url) || url == null || typeof (url) == "undefined") {
      urls = '/erp/purchase/unitOption/unitOptionByNum'
    } else {
      urls = url
    }
    return this.http.post(urls, { switchUnitId: switchUnitId, unitCode: unitNum, unitType: unitType, type: unitType }, httpOptions);
  }


  /**
   * url获取参数值
   */
  GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);//search,查询？后面的参数，并匹配正则
    if (r != null) return unescape(r[2]); return null;
  }

  /**
   * string字符串获取参数值
   * indexOf获取字符下标位置
   */
  GetString(str, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var p = str.substring(str.indexOf('?') + 1, str.length)
    var r = p.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
  }

  /**
   * string字符串获取参数值
   * indexOf获取字符下标位置
   */
  GetString2(str, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var p = str.substring(str.indexOf('?') + 1, str.length)
    var r = p.substr(0).match(reg);
    if (r != null) return unescape(r[2]); return null;
  }

  /**
   * 三目判断对象是否存在数据值并返回相应参数
   * e：传入对象
   * retu：默认返回对象，'',0,[],true,false (正常布尔值false会当成字符串判断为返回true，序列化后正常)
   */
  returnData(e, retu) {
    if (retu === '[]') {
      if (JSON.stringify(e) == '[]') {
        return []
      } else {
        return typeof (e) !== 'string' ? e : JSON.parse(e)
      }
    } if (retu === true || retu === false) {
      return JSON.parse(e)
    } else {
      return e == undefined || typeof (e) == "undefined" || e == "undefined" || e == null || e == 'null' || e == '' ? retu : e
    }
  }


  getPages(pageUrl, pageIndex: number, pageSize: number): Observable<{}> {
    let params = new HttpParams()
      .append('page', `${pageIndex}`)
      .append('size', `${pageSize}`);
    // .append('results', `${pageSize}`);
    return this.http.get(`${pageUrl}`, { params });

    // this.http.get(`${this.randomUserUrl}`, {params}).subscribe((response:any) => {			//.subscribe获取服务器数据
    //   console.log(response);
    //   // this.listdata=response.result;            
    // });

  }


  /**
   * 选项卡操作
   */
  resetTableSize() {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd))
      .subscribe((event) => {
        const tabUrl = window.location.pathname.substring(10, window.location.pathname.length);//选项卡路由地址
        const urlThis = localStorage.getItem('urlThis')//报表查看完整跳转地址
        const tabTitle = localStorage.getItem('tabTitle')//当前模块权限名称
        const privIds = this.GetQueryString("privId");//当前模块权限id
        const selectData = this.GetQueryString("selectData");//是否为报表查看新开跳转
        const isState = this.utilService.isState[privIds];//当前模块操作状态
        const isCache = this.utilService.isCache[privIds];//当前模块单据明细缓存状态
        const isRoute = localStorage.getItem('isRoute');//当前模块打开状态
        // console.log(urlThis,tabTitle,isRoute)
        $('.' + privIds + ' button.tabBlock').click();
        $(window).resize();
        $('.layui-table-tips .layui-layer-content i.layui-icon-close').click();
        if (isRoute === '1') {//选项卡已打开状态
          if (selectData) {//报表查看新开跳转
            if (isState == -1 && !isCache) {//模块非操作状态
              setTimeout(() => {
                $('nz-tag.active .ng-trigger i').click();
                this.utilService.goTo(urlThis);
              }, this.utilService.setTime1);
            } else {
              this.utilService.msg(tabTitle);
              localStorage.removeItem(selectData)
              if (localStorage.getItem('urlData')) {
                var urlData = JSON.parse(localStorage.getItem('urlData'));
                var urlNext = this.utilService.urlNext(selectData, urlData);
                if (urlNext) {
                  this.utilService.goTo(urlNext);
                }
              }
            }
          }
          this.loadClose();
        } else {
          if (tabTitle) {
            this.loadOpen();
          }
        }

      });

    /* this.router.events.subscribe((event) => {
      if(event instanceof NavigationStart) {
        console.log('NavigationStart 开始导航',event)
        this.utilService.itemMenu=false;
      } else if(event instanceof NavigationEnd) {
        console.log('NavigationEnd 结束',event)
        this.utilService.itemMenu=true;
      } else if(event instanceof NavigationCancel) {
        console.log('NavigationCancel 取消导航',event)
      } else if(event instanceof NavigationError) {
        console.log('NavigationError 导航出错',event)
      } else if(event instanceof RoutesRecognized) {
        console.log('RoutesRecognized 路由已认证',event)
      }
    }); */
  }

  loadIndex;
  loadOpen() {
    this.loadIndex = layer.load();
    /* this.loadIndex = layer.load(1, {
      shadeClose: false,
      title: '加载中..',
      shade: [0.5, '#000']
    }); */
  }
  loadClose() {
    layer.close(this.loadIndex);
  }

  /**
   * 选项卡新开或切换读取url跳转
   */
  urlTable(module) {
    var urlKey = this.GetQueryString('selectData');
    if (localStorage.getItem('urlData') && localStorage.getItem(urlKey)) {
      var urlData = JSON.parse(localStorage.getItem('urlData'));
      var urlParm = this.utilService.urlParm(urlKey, urlData);
      for (let i in urlParm) {
        module['searchData'][i] = urlParm[i] == null ? "" : urlParm[i]
      }
    }
  }

  urlNext() {
    var urlKey = this.GetQueryString('selectData');
    localStorage.removeItem(urlKey)
    if (localStorage.getItem('urlData')) {
      var urlData = JSON.parse(localStorage.getItem('urlData'));
      var urlNext = this.utilService.urlNext(urlKey, urlData);
      if (urlNext) {
        this.utilService.goTo(urlNext);
      }
    }
    this.loadClose();
  }

  constructor(public router: Router, private http: HttpClient, public utilService: UtilService, private nzMessageService: NzMessageService) {
  }


}
